class WatchCollectFactory {
  RefWatch instance;
  List<dynamic> refs = [];
  WatchCollectFactory(this.instance);

  dispose() {
    // 清除依赖
    refs.forEach((ele) {
      ele.dispose(this);
    });
  }
}

late dynamic globalRefWatchInstance = '';
typedef ReckonCallback = dynamic Function();
typedef HanderCallback = Function(dynamic oldVal, dynamic newVal);

class RefWatch {
  /// 函数，返回一个值
  late ReckonCallback _reckon;

  /// 函数，当执行_reckon所获取的结果发生改变时执行
  /// [oldVal] 旧值
  /// [newVal] 新值
  late HanderCallback _handler;

  // 缓存的值
  late dynamic _value;
  late WatchCollectFactory _watchCollector;

  RefWatch(this._reckon, this._handler) {
    _watchCollector = WatchCollectFactory(this);
    _value = _excute();
  }

  _excute() {
    globalRefWatchInstance = _watchCollector;
    dynamic result = _reckon();
    globalRefWatchInstance = null;
    return result;
  }

  /// 自动执行事件（请勿调用）
  excute() {
    // 如果不相等，触发依赖
    dynamic currentValue = _excute();
    if (currentValue != _value) {
      try {
        _handler(_value, currentValue);
        _value = currentValue;
      } catch (e) {
        dispose(); // 销毁无用的依赖
        print('app wrong: RefWatch excute 执行出错.');
        print('存在未清除的watch依赖！请调用dispose方法清除依赖');
      }
    }
  }

  /// 清除watch缓存
  ///
  /// (请务必widget卸载的时候清除依赖)
  dispose() {
    _watchCollector.dispose();
  }
}
